<template>
	<div class="zh-video-watermark">
        <nav-header>
			<div class="zh-h5-nav">
				<div 
					:class="activePanel === 'video-watermark' ? 'active' : ''"
					@click="changePanel('video-watermark')">视频水印</div>
				<div 
					:class="activePanel === 'record' ? 'active' : ''" 
					@click="changePanel('record')">历史水印记录</div>
			</div>
		</nav-header>

		<transition name="fade" mode="out-in" v-if="activePanel === 'video-watermark'" >
			<div class="zh-watermark" 
				v-loading="loading.status"
				:element-loading-text="loading.txt">
				<div class="zh-switch">
					<el-switch
					  	v-model="isSwitch"
					  	@change="openWaterMark"
					  	active-color="#13ce66"
  						inactive-color="#dcdfe6"
  						active-text="开启水印"
  						inactive-text="不开启水印"
					>
					</el-switch>
				</div>
				<div class="zh-examples-box" v-if="this.isSwitch === true">
					<div class="zh-examples">视频水印示例</div>
					<div class="zh-video-examples" id="zh-video-examples">
						<div class="zh-canvas"
						 	v-if="this.waterMarkType === '1'" 
							v-drag
							id="drag"
							:style="style"
						>
							<div>{{attributesValue}}</div>
						</div>
						<div class="zh-canvas" 
							v-if="this.waterMarkType === '2'"
							v-dragImg
							id="dragImg"
							:style="styleImg"
						>
							<img 
								:src="previewImgURL" alt="" 
								@dragstart.stop="dragOver($event)"
								draggable="false"
							>
						</div>
					</div>
					<div class="zh-attributes">
						<el-radio v-model="waterMarkType" label="1">文字水印</el-radio>
						<el-radio v-model="waterMarkType" label="2">图片水印</el-radio>
						<div class="attributes-all" v-if="this.waterMarkType === '1'">
							<div class="attributes-list">
								<span>水印名称</span>
								<el-input 
									v-model="attributesValue"
									@blur="attributes"
									class="list-select"
									placeholder="请输入内容（10字以内）" 
									:maxlength="parseInt(10)" 
									clearable>
								</el-input>
							</div>
							<div class="attributes-list">
								<span>字体设置</span>
								<el-select 
									filterable
									v-model="font" 
									@change="fontSize"
									placeholder="请选择" 
									class="list-select">
								    <el-option
								      v-for="item in options"
								      :key="item.value"
								      :label="item.label"
								      :value="item.value"
								      >
								    </el-option>
								</el-select>
								<el-switch
								  	v-model="isCrude"
								  	@change="fontWeight"
								  	active-color="#13ce66"
			  						inactive-color="#dcdfe6"
			  						active-text="加粗"
			  						inactive-text="正常"
			  						class="list-switch"
								>
								</el-switch>
								<el-color-picker color-format="rgb" v-model="color" @change="coloring"></el-color-picker>
							</div>
						</div>
						<div class="upload-picture" v-if="this.waterMarkType === '2'">
							<!-- <el-button type="primary">点击上传</el-button> -->
							 <uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @files-submitted="fileSubmit" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail"  class="uploader-example" style="width:100px;float:left">
							    <uploader-unsupport></uploader-unsupport>
							    <uploader-btn :directory="false" :attrs="attrs"  :single="true">{{uploadButtonTxt}}</uploader-btn>
							    <!-- <uploader-list></uploader-list> -->
							  </uploader>
							<div class="input-number">
								<span>图片大小</span>&nbsp;
								<el-input-number 
									v-model="widthNum" 
									@change="widthNumber"
									controls-position="right" 
									:min="1" :max="200">
								</el-input-number>
								-
								<el-input-number 
									v-model="heightNum" 
									@change="heightNumber"
									controls-position="right" 
									:min="1" :max="200">
								</el-input-number>
							</div>
						</div>
					</div>
					<div class="zh-button">
						<el-button type="primary" round @click="resetForm">重置</el-button>
						<el-button type="primary" round @click="checkSaveOP">确定</el-button>
					</div>
				</div>
			</div>
		</transition>
		<transition name="fade" mode="out-in" v-if="activePanel === 'record'" >
			<zh-watermark-record />
		</transition>
	</div>
</template>
<script>
	var parentWidth = 720;
	var parentHeight = 400;
	var HORIZONTAL = 0 ;
    var UPRIGHT = 0;
    import {uploaderFileFail} from './../../../tools/tool';

  	export default {
	    data() {
		    return {
		    	loading:{
					status:false,
					txt:'获取数据...',
				},
		    	openPram:{
		    		open:1,
		    		id:0,
		    	},
		    	uploadButtonTxt:'选择图片',
		    	activePanel: 'video-watermark',
		    	isSwitch: false,
		    	attributesValue: '',
                waterMarkType: '1',
                imageType: ['image/jpeg', 'image/bmp', 'image/png'], // 上传图片格式
		    	font: '20',
		    	options: [{
		    		value: '20',
          			label: '20号'
		    	},{
		    		value: '22',
          			label: '22号'
		    	},{
		    		value: '26',
          			label: '26号'
		    	},{
		    		value: '28',
          			label: '28号'
		    	},{
		    		value: '36',
          			label: '36号'
		    	},{
		    		value: '48',
          			label: '48号'
		    	},{
		    		value: '56',
          			label: '56号'
		    	},],
		    	isCrude: false,
		    	color: 'rgb(0, 0, 0)',
		    	widthNum: '200',
		    	heightNum: '100',
		    	style: {
                    width: '',
                    height: '',
                    top: '',
                    left: '',
                    fontSize: '20px',
                    color: 'rgb(0, 0, 0)',
                    fontWeight: '',
                },
                styleImg: {
                    width: '',
                    height: '',
                    top: '0px',
                    left: '0px',
                },
                attrs: {
			      	accept: ['image/*']
			    },
                uploadOptions: {
			          target: this.BASE_URL+'/api/resource/res_upload',
			          testChunks: false,
			          headers:{Authorization : `Bearer `+this.$g.access_token},
			    },
			    statusText: {
			      	success: '上传成功',  
			      	error: '上传出错',  
			     	uploading: '正在上传...',  
			      	paused: '暂停',  
			      	waiting: '等待上传'  
				},
				uploadInfo:{
					file_name:'',
					file_path:'',
					file_size:0
				},
				previewImgURL:'',
				selectFileOrNot:false,
		    }
		},
		created(){
			this.toggleView()
			this.widthNumber()
			this.heightNumber()
			this.getWorkingMark()
	    },
	    computed: {
	    	
	    	// 图片大小计算属性
	        widthNumpx(){
	    		return this.widthNum + 'px'
	    	},
	    	heightNumpx(){
	    		return this.heightNum + 'px'
	    	},
	    },
	    watch:{
	    	$route(){
	    		this.toggleView()
	    	},
	    	'attributesValue'(){
	    		if(this.attributesValue === '') {
	    			this.style.top = '0'
					this.style.left = '0'
					this.style.width = 'auto'
	    		}
	    	},
	    	'waterMarkType'(){
	    		if( this.waterMarkType === '2' ){
	    			this.uploadButtonTxt = '选择图片'
	    		}
	    	}

	    },
		methods: { 
			resetForm(){
				this.widthNumber()
				this.heightNumber()
				this.getWorkingMark()
			},
			changePanel(panel){
	    		this.activePanel = panel;
	    	},
			openWaterMark(){
				if( this.isSwitch ){
					this.openPram.open = 1;
				}else{
					this.openPram.open = 0;
				}
				if( parseInt(this.openPram.id)  > 0 ){
					let success = ( data=>{
	            		this.$message.success(data.msg)
	            	})
	            	
	            	this.$ajax.post('api/setting/open_watermark',this.openPram,{func:{success:success}})
				}
				
			},
			checkSaveOP(){
				if(this.attributesValue.trim() === '' && this.waterMarkType.toString() === '1') {
					this.$message.error('请输入水印名称');
					return;
	    		}
				if( this.waterMarkType.toString() === '1' ){
					this.saveMarkTxt();
				}else{
					if( this.selectFileOrNot ){
						this.fileUpload();
					}else{
						this.saveMarkImg();
					}
					
				}
			},
			fileUpload(){
				this.$refs.uploader.uploader.upload();
			},
			//上传成功的事件  
			fileSuccess ( rootFile, file, message, chunk ) { 
				this.selectFileOrNot = false;
                var mess = eval('(' + message + ')');
                mess = handleResponseData( mess );
                
			 	if(parseInt( mess.data.status ) === 1 ){
			  		this.uploadInfo.file_name = mess.data.file_name;
			  		this.uploadInfo.file_path = mess.data.file_path;
			  		this.uploadInfo.post_fix = mess.data.post_fix;
			  		this.saveMarkImg();
			  }
			},
			fileFail(rootFile, file, message, chunk) {
                uploaderFileFail(this, this.$refs.uploader.uploader, file, message);
			},
			//过滤文件格式
			fileSubmit(files, fileList, event){
				for (var i = 0 ; i < fileList.length ; i++ ) {
					let file_type = fileList[i].fileType.toLocaleLowerCase();

                    if(!this.imageType.includes(file_type)){
                        this.$message.warning('只允许上传 bmp/jpg/jpeg/png 格式图片');
						this.$refs.uploader.uploader.removeFile( fileList[i] );
					}else if( fileList[i].size > 10240000 ){
						this.$message.warning('只允许上传10M以内的文件');
						this.$refs.uploader.uploader.removeFile( fileList[i] );
					}else{
						if( this.$refs.uploader.uploader.fileList.length  > 1  ){
							//删除第一张图片
							this.$refs.uploader.uploader.removeFile( this.$refs.uploader.uploader.fileList[0] );
						}
					 	this.previewImgURL = window.URL.createObjectURL(fileList[i].file)
						this.uploadButtonTxt = '更换图片';
						this.uploadInfo.file_size = fileList[i].size;
						this.selectFileOrNot = true;
					}
					
					
				}
				
			},
		
			fileRemoved(file){
				this.selectFileOrNot = false;
			},
			getWorkingMark(){

				this.loading.status = true;
				let success = ( data=>{
            		this.loading.status = false;
            		var result = data.data;
            		if( is_empty( result )){
            			this.isSwitch = false;
            		}else{
            			this.waterMarkType = data.data.watermark_type.toString();
            			this.openPram.id = result.id;
            			this.isSwitch = parseInt(result.open) === 1?true:false;
            			if( data.data.watermark_type.toString() === '1' ){
	            			//:::::::::::::::::::::::TODO 偏移量
	            			this.style.fontSize = result.font_size+'px';
	            			this.style.left = parentWidth*(result.horizontal/100)+'px'
	            			this.style.top = parentHeight*(result.upright/100)+'px'
							this.attributesValue = result.name;
							this.font = result.font_size.toString();
							HORIZONTAL = Math.round(result.horizontal);
                       		UPRIGHT = Math.round(result.upright);
							this.isCrude = parseInt(data.overstriking) === 1 ? true:false;
							this.color = result.color;
							this.style.color = this.color
	            		}else{
	            			//:::::::::::::::::::::::TODO 偏移量
	            			this.styleImg.width = result.size_width
                    		this.styleImg.height = result.size_height;
	            			this.styleImg.left = parentWidth*(result.horizontal/100)+'px'
	            			this.styleImg.top = parentHeight*(result.upright/100)+'px'
	            			HORIZONTAL = Math.round(result.horizontal);
                       		UPRIGHT = Math.round(result.upright);
	            			this.widthNum = result.size_width;
	            			this.heightNum = result.size_height;
	            			this.uploadInfo.file_path = result.watermark_path;
	            			this.previewImgURL = this.BASE_URL + result.watermark_path;
	            		}
            			
            		}
            		
            	})
            	let fail = ( data => {
            		this.loading.status = false;
            		this.$message.error(data.msg)
            	})
            	this.$ajax.get('api/setting/working_watermark',{params: {},func:{success:success,fail:fail}})
			},
			
			saveMarkTxt(){
				let success = ( data=>{
            		this.$message.success(data.msg)
            		this.getWorkingMark();
            	})
            	var params = {
            		watermark_name:this.attributesValue,
            		horizontal:HORIZONTAL,
            		upright:UPRIGHT,
					w_font_size:this.font,
					w_overstriking:this.isCrude?1:0,
					w_color:this.color,

            	}
            	this.$ajax.post('api/setting/watermark_txt',params,{func:{success:success}})
			},
			saveMarkImg(){

				let success = ( data=>{
            		this.$message.success(data.msg)
            		this.getWorkingMark();
            	})
            	var params = {
            		horizontal:HORIZONTAL,
            		upright:UPRIGHT,
					size_width:this.widthNum,
					size_height:this.heightNum,
					watermark_pic:this.uploadInfo.file_path,
					id:this.openPram.id,
            	}
            	this.$ajax.post('api/setting/watermark_img',params,{func:{success:success}})
			},
			move(e){
				// let odiv = e.target; //获取目标元素
				// //算出鼠标相对元素的位置
    //             let disX = e.clientX - odiv.offsetLeft;
    //             let disY = e.clientY - odiv.offsetTop;
				// let parentWidth = document.getElementById('zh-video-examples').clientWidth;
				// let parentHeight = document.getElementById('zh-video-examples').clientHeight;
    //         	let childWidth = document.getElementById('dragImg').offsetWidth;
    //         	let childHeight = document.getElementById('dragImg').offsetHeight;
    //             document.onmousemove = (e) => { //鼠标按下并移动的事件
    //               	//用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
    //                 let x = e.clientX - disX;
    //                 let y = e.clientY - disY;

    //                 let xMax = parentWidth-childWidth;
    //                 let xMin = 0;
    //                 let yMax = parentHeight-childHeight;
    //                 let yMin = 0;

    //                 if ( x >= xMax ) {
    //                   	x = xMax;
    //                 } else if ( x <= xMin ) {
    //                   	x = xMin;
    //                 }

    //                 if ( y >= yMax ){
    //                   	y = yMax;
    //                 } else if ( y <= yMin ){
    //                   	y = yMin;
    //                 }

    //               	//移动当前元素  
    //                 this.styleImg.left = x + 'px';
    //                 this.styleImg.top = y + 'px';


    //             };
    //             document.onmouseup = (e) => {
    //                 document.onmousemove = null;
    //                 document.onmouseup = null;
    //             };
			},
			// 图片大小
			widthNumber(){
				this.styleImg.width = this.widthNumpx
			},
			heightNumber(){
				this.styleImg.height = this.heightNumpx
			},
			//禁止原有默认事件
            dragOver(event){
                event.preventDefault()
                event.stopPropagation()
            },
			attributes(){
				if(this.attributesValue.trim() === '' && this.waterMarkType === 1) {
					this.$message.error('请输入水印名称');
	    			this.widthAndHeight()
	    		}
			},
			fontWeight(){
				if (this.isCrude !== false) {
					this.style.fontWeight = '800'
				} else if (this.isCrude !== true) {
					this.style.fontWeight = '100'
				}
			},
			coloring(){
				this.style.color = this.color
			},
			widthAndHeight(){
				this.style.top = '0'
				this.style.left = '0'
				this.style.width = 'auto'
			},
			fontSize(){
				this.widthAndHeight()
				this.style.fontSize = this.font +'px'
			},
			//记录导航状态
		    toggleView(){
		   		this.view = this.$route.name
		    },
		    videoWatermark(){
		    	this.$router.push("/resources/video/video-watermark")
		    },
		    watermarkRecord(){
		    	this.$router.push("/resources/video/video-watermark/record")
		    },
		    handleSizeChange(val) {
		    },
		    handleCurrentChange(val) {
		    }
		},
        directives:{//自定义拖拽事件
            drag(el){
                el.onmousedown = function (e) {
                 //鼠标按下，计算当前元素距离可视区的距离
                    let disX = e.clientX - el.offsetLeft;
                    let disY = e.clientY - el.offsetTop;
 					
                	let childWidth = document.getElementById('drag').offsetWidth;
                	let childHeight = document.getElementById('drag').offsetHeight;
                	el.style.width = 'auto';
                    document.onmousemove = function (e) {
                      	//通过事件委托，计算移动的距离 
                        let x = e.clientX - disX;
                        let y = e.clientY - disY;

                        let xMax = parentWidth-childWidth;
                        let xMin = 0;
                        let yMax = parentHeight-childHeight;
                        let yMin = 0;
                        el.style.width = 'auto';
                        if ( x >= xMax ) {
                        	el.style.width = 'auto';
                        	el.style.width = (childWidth + 1) + 'px';
                          	x = xMax;
                        } else if ( x <= xMin ) {
                          	x = xMin;
                        }

                        if ( y >= yMax ){
                          	y = yMax;
                        } else if ( y <= yMin ){
                          	y = yMin;
                        }

                      	//移动当前元素  
                        el.style.left = x + 'px';
                        el.style.top = y + 'px';

                    };
                    document.onmouseup = function (e) {
                    	//通过事件委托，计算移动的距离 
                        let x = e.clientX - disX;
                        let y = e.clientY - disY;

                        let xMax = parentWidth-childWidth;
                        let xMin = 0;
                        let yMax = parentHeight-childHeight;
                        let yMin = 0;

                        if ( x >= xMax ) {
                          	x = xMax;
                        } else if ( x <= xMin ) {
                          	x = xMin;
                        }

                        if ( y >= yMax ){
                          	y = yMax;
                        } else if ( y <= yMin ){
                          	y = yMin;
                        }

                      	//移动当前元素  
                        el.style.left = x + 'px';
                        el.style.top = y + 'px';
                        HORIZONTAL = Math.round(x/parentWidth*100);
                        UPRIGHT = Math.round(y/parentHeight*100);
                        document.onmousemove = null;
                        document.onmouseup = null;
                    };
                };
            },
            dragImg(el){
                el.onmousedown = function (e) {
                 //鼠标按下，计算当前元素距离可视区的距离
                    let disX = e.clientX - el.offsetLeft;
                    let disY = e.clientY - el.offsetTop;
 					
                	let childWidth = document.getElementById('dragImg').offsetWidth;
                	let childHeight = document.getElementById('dragImg').offsetHeight;
                    document.onmousemove = function (e) {
                      	//通过事件委托，计算移动的距离 
                        let x = e.clientX - disX;
                        let y = e.clientY - disY;

                        let xMax = parentWidth-childWidth;
                        let xMin = 0;
                        let yMax = parentHeight-childHeight;
                        let yMin = 0;

                        if ( x >= xMax ) {
                          	x = xMax;
                        } else if ( x <= xMin ) {
                          	x = xMin;
                        }

                        if ( y >= yMax ){
                          	y = yMax;
                        } else if ( y <= yMin ){
                          	y = yMin;
                        }

                      	//移动当前元素  
                        el.style.left = x + 'px';
                        el.style.top = y + 'px';

                    };
                    document.onmouseup = function (e) {
                    	//通过事件委托，计算移动的距离 
                        let x = e.clientX - disX;
                        let y = e.clientY - disY;

                        let xMax = parentWidth-childWidth;
                        let xMin = 0;
                        let yMax = parentHeight-childHeight;
                        let yMin = 0;

                        if ( x >= xMax ) {
                          	x = xMax;
                        } else if ( x <= xMin ) {
                          	x = xMin;
                        }

                        if ( y >= yMax ){
                          	y = yMax;
                        } else if ( y <= yMin ){
                          	y = yMin;
                        }

                      	//移动当前元素  
                        el.style.left = x + 'px';
                        el.style.top = y + 'px';
                        HORIZONTAL = Math.round(x/parentWidth*100);
                        UPRIGHT = Math.round(y/parentHeight*100);
                        document.onmousemove = null;
                        document.onmouseup = null;
                    };
                };
            },
        },
        mounted () {  
		// 获取uploader对象  
		  this.$nextTick(() => {  
		  //  window.Uploader = this.$refs.uploader.uploader  
		  })  
		}  
  	}
</script>
<style lang="scss">
	.zh-video-watermark {
		.zh-watermark {
			padding-left: 20px;
			.zh-switch {
				padding: 30px 0;
			}
			.zh-examples-box {
				width: 720px;
			}
			.zh-examples {
				padding-bottom: 20px;
			}
			.zh-video-examples {
				background:url('/static/image/watermark_bg.png') no-repeat;
				position: relative;
				width: 100%;
				height: 400px;
				border: 1px solid #e6e6e6;
				overflow: hidden;
				.zh-canvas {
					position: absolute;
					top: 0;
		            left: 0;
		            moz-user-select: -moz-none; 
		            -moz-user-select: none; 
		            -o-user-select:none; 
		            -khtml-user-select:none; 
		            -webkit-user-select:none; 
		            -ms-user-select:none; 
		            user-select:none;
		            cursor: default;
		            #drag {
		            	padding: 0 2px;
		            }
		            img {
		            	width: 100%;
		            	height: 100%;
		            }
				}
			}
			.zh-button {
				padding: 30px 0 10px;
				text-align: center;
				button {
					min-width: 80px;
				}
			}
			.zh-attributes {
				padding-left: 20px;
				.attributes-all {
					padding-bottom: 20px;
					border-bottom: 1px solid #e6e6e6;
				}
				.attributes-list {
					margin-bottom: 20px;
					.list-select {
						width: 200px;
						margin-left: 5px;
					}
					.el-color-picker__trigger {
						vertical-align: middle;
					}
					.list-switch {
						margin: 0 20px;
					}
				}
				.el-radio {
					padding: 30px 0;
				}
				.upload-picture {
					padding-bottom: 40px; 
					border-bottom: 1px solid #e6e6e6;
				}
				.input-number {
					display: inline-block;
					margin-left: 20px;
				}
			}
			.uploader-btn{
				padding: 0;
				border: 0;
				color: #fff;
				background-color: #409EFF;
				border-color: #409EFF;
				width: 80px;
				height: 30px;
				line-height: 30px;
				text-align: center;
			}
		}
	}
</style>